import requests
import sys
from tqdm import tqdm


def fix_encoding(query):
    """
    Encoding fixes for Python 2 and Python 3 cross-compatibilty.
    """
    if sys.version_info > (3, 0):
        return query
    else:
        return query.encode("utf-8")


def sanitize_title(title):
    """
    Remove forbidden characters from title that will prevent Windows
    from creating directory.

    Also change ' ' to '_' to preserve previous behavior.
    """
    forbidden_chars = ' *"/\<>:|(),'
    replace_char = "_"

    for ch in forbidden_chars:
        title = title.replace(ch, replace_char)

    return title


def download_stream(url, filepath):
    """
    Stream stuff from the Internet to a local file.
    """
    
    ### Added progress bar
    response = requests.get(url, stream=True)
    
    total_size = int(response.headers.get('content-length', 0))
    block_size = 1024
    wrote = 0
    
    t = tqdm(total=total_size, unit='B', unit_scale=True, desc='Downloading')
    
    with open(filepath, "wb") as out_file:
        for data in response.iter_content(block_size):
            t.update(len(data))
            wrote = wrote  + len(data)
            out_file.write(data)
        t.close()
        
        if total_size != 0 and wrote != total_size:
            print("ERROR, something went wrong")
            